#!/usr/bin/env node

/**
 * 创建测试Excel文件并执行完整导入流程
 */

const XLSX = require('xlsx');
const fs = require('fs');
const path = require('path');
const axios = require('axios');
const FormData = require('form-data');

class ExcelImportTester {
  constructor() {
    this.baseDir = '/Users/andylau/Dropbox/AppDevelopment/CMB250716';
    this.token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOjEsImVtYWlsIjoiYWRtaW5AZXhhbXBsZS5jb20iLCJtZW1iZXJzaGlwTGV2ZWwiOiJhZG1pbiIsImlhdCI6MTc1NzE2NDAyMCwiZXhwIjoxNzU3NzY4ODIwLCJpc3MiOiJjdS1tci1idWxsLWFwaSJ9.2pqn01o6rqlOOoOGaEPXNtwIoK-A86kPty3KWnyvY0Q';
    this.timestamp = Date.now();
  }

  log(message, type = 'info') {
    const timestamp = new Date().toISOString();
    const prefix = {
      'info': '🔍',
      'success': '✅',
      'error': '❌',
      'fix': '🔧'
    }[type] || 'ℹ️';
    console.log(`${prefix} [${timestamp}] ${message}`);
  }

  createExcelFile() {
    this.log('创建新的测试Excel文件');
    
    const workbook = XLSX.utils.book_new();
    
    // Dishes工作表
    const dishesData = [
      ['dish_sku', 'dish_slug', 'name_zh', 'name_en', 'category', 'base_status', 'description_zh', 'description_en', 'ingredients_zh', 'ingredients_en', 'tags', 'popularity'],
      [`TEST_${this.timestamp}_001`, `test-burger-${this.timestamp}`, `测试汉堡_${this.timestamp}`, `Test Burger ${this.timestamp}`, '主食', 'active', '这是测试汉堡描述', 'This is test burger description', '牛肉,生菜,面包', 'Beef, Lettuce, Bread', '测试,汉堡', '85'],
      [`TEST_${this.timestamp}_002`, `test-drink-${this.timestamp}`, `测试饮料_${this.timestamp}`, `Test Drink ${this.timestamp}`, '饮品', 'active', '这是测试饮料描述', 'This is test drink description', '水,糖,柠檬', 'Water, Sugar, Lemon', '测试,饮料', '75']
    ];
    
    const dishesWS = XLSX.utils.aoa_to_sheet(dishesData);
    XLSX.utils.book_append_sheet(workbook, dishesWS, 'Dishes');
    
    // Variants工作表
    const variantsData = [
      ['dish_sku', 'name_zh', 'variant_code', 'variant_name', 'price', 'compare_at_price', 'is_default', 'stock'],
      [`TEST_${this.timestamp}_001`, '标准', 'STD-001', 'Standard', '25.99', '', 'true', '100'],
      [`TEST_${this.timestamp}_002`, '中杯', 'MED-001', 'Medium', '12.99', '', 'true', '150']
    ];
    
    const variantsWS = XLSX.utils.aoa_to_sheet(variantsData);
    XLSX.utils.book_append_sheet(workbook, variantsWS, 'Variants');
    
    // Options工作表
    const optionsData = [
      ['dish_sku', 'name_zh', 'group_code', 'group_name', 'required', 'value_code', 'value_name', 'price_delta'],
      [`TEST_${this.timestamp}_001`, '配菜选择', 'SIDE', '配菜', 'false', 'FRIES', '薯条', '3.00'],
      [`TEST_${this.timestamp}_002`, '温度选择', 'TEMP', '温度', 'true', 'ICE', '冰', '0']
    ];
    
    const optionsWS = XLSX.utils.aoa_to_sheet(optionsData);
    XLSX.utils.book_append_sheet(workbook, optionsWS, 'Options');
    
    const fileName = `test_excel_${this.timestamp}.xlsx`;
    const filePath = path.join(this.baseDir, fileName);
    
    XLSX.writeFile(workbook, filePath);
    
    this.log(`Excel文件已创建: ${fileName}`, 'success');
    return { fileName, filePath };
  }

  async validateExcel(filePath) {
    this.log('开始V2验证');
    
    const form = new FormData();
    form.append('file', fs.createReadStream(filePath));
    
    try {
      const response = await axios.post('http://localhost:3001/api/admin/menu-import/v2/validate', form, {
        headers: {
          ...form.getHeaders(),
          'Authorization': `Bearer ${this.token}`
        },
        timeout: 60000
      });
      
      this.log('验证响应: ' + JSON.stringify(response.data), 'success');
      return response.data;
    } catch (error) {
      this.log('验证失败: ' + error.message, 'error');
      throw error;
    }
  }

  async waitForValidation(jobId) {
    this.log('等待验证完成');
    
    let attempts = 0;
    const maxAttempts = 30;
    
    while (attempts < maxAttempts) {
      try {
        const response = await axios.get(`http://localhost:3001/api/admin/menu-import/v2/jobs/${jobId}`, {
          headers: {
            'Authorization': `Bearer ${this.token}`
          }
        });
        
        const status = response.data.status;
        this.log(`第${attempts + 1}次检查，状态: ${status}`);
        
        if (status === 'validated') {
          this.log('验证完成', 'success');
          return response.data;
        } else if (status === 'failed') {
          throw new Error('验证失败');
        }
        
        await new Promise(resolve => setTimeout(resolve, 1000));
        attempts++;
      } catch (error) {
        this.log('状态检查失败: ' + error.message, 'error');
        throw error;
      }
    }
    
    throw new Error('验证超时');
  }

  async commitImport(jobId) {
    this.log('开始提交导入');
    
    try {
      const response = await axios.post(`http://localhost:3001/api/admin/menu-import/v2/commit?job_id=${jobId}`, {}, {
        headers: {
          'Authorization': `Bearer ${this.token}`,
          'Content-Type': 'application/json'
        },
        timeout: 60000
      });
      
      this.log('提交响应: ' + JSON.stringify(response.data), 'success');
      return response.data;
    } catch (error) {
      this.log('提交失败: ' + error.message, 'error');
      throw error;
    }
  }

  async checkDatabase() {
    this.log('检查数据库状态');
    
    try {
      const response = await axios.get('http://localhost:3001/api/menu/public/items', {
        headers: {
          'Authorization': `Bearer ${this.token}`
        }
      });
      
      const items = response.data.data.items;
      this.log(`数据库中共有 ${items.length} 条数据`);
      
      // 查找测试数据
      const testItems = items.filter(item => item.name.includes(`${this.timestamp}`));
      if (testItems.length > 0) {
        this.log(`找到 ${testItems.length} 条测试数据:`, 'success');
        testItems.forEach(item => {
          this.log(`- ${item.name}: ${item.description}`);
        });
        return true;
      } else {
        this.log('未找到测试数据', 'error');
        return false;
      }
    } catch (error) {
      this.log('数据库检查失败: ' + error.message, 'error');
      return false;
    }
  }

  async run() {
    console.log('\n' + '='.repeat(60));
    console.log('🎯 Excel导入完整测试');
    console.log('='.repeat(60) + '\n');
    
    try {
      // 1. 创建Excel文件
      const { filePath } = this.createExcelFile();
      
      // 2. 验证Excel
      const validateResult = await this.validateExcel(filePath);
      const jobId = validateResult.job_id;
      
      if (!jobId) {
        throw new Error('未获取到任务ID');
      }
      
      // 3. 等待验证完成
      await this.waitForValidation(jobId);
      
      // 4. 提交导入
      const commitResult = await this.commitImport(jobId);
      
      if (!commitResult.success) {
        throw new Error('提交失败: ' + commitResult.message);
      }
      
      // 5. 检查数据库
      const dbCheck = await this.checkDatabase();
      
      console.log('\n' + '='.repeat(60));
      if (dbCheck) {
        console.log('🎉 Excel导入测试成功！');
        console.log('✅ 数据已正确导入并保存到数据库！');
      } else {
        console.log('❌ Excel导入测试失败！');
        console.log('💡 数据未正确保存到数据库');
      }
      console.log('='.repeat(60) + '\n');
      
    } catch (error) {
      console.log('\n' + '='.repeat(60));
      console.log('❌ Excel导入测试失败！');
      console.log('错误:', error.message);
      console.log('='.repeat(60) + '\n');
    }
  }
}

// 立即运行
if (require.main === module) {
  const tester = new ExcelImportTester();
  tester.run().catch(console.error);
}

module.exports = ExcelImportTester;